package swingxrcp.framework.server.spring;

import java.io.IOException;
import java.util.Collection;

import org.springframework.beans.BeansException;
import org.springframework.beans.factory.config.ConfigurableListableBeanFactory;
import org.springframework.beans.factory.support.DefaultListableBeanFactory;
import org.springframework.context.annotation.ClassPathBeanDefinitionScanner;
import org.springframework.core.type.filter.AnnotationTypeFilter;
import org.springframework.web.context.support.AbstractRefreshableWebApplicationContext;

import swingxrcp.framework.server.bean.Bean;
import swingxrcp.framework.server.environment.Environment;
import swingxrcp.framework.server.environment.Module;

/**
 * Spring的Beans配置供给方案(实现各模块的beans.xml自动装配)
 *
 * @author 梁飞
 *
 */
public class FrameworkContext extends AbstractRefreshableWebApplicationContext {

	protected void loadBeanDefinitions(DefaultListableBeanFactory beanFactory)
			throws IOException, BeansException {
		// 创建@Bean注解的扫描器
		ClassPathBeanDefinitionScanner scanner = new ClassPathBeanDefinitionScanner(beanFactory);
		// 注册@Bean注解
		scanner.addIncludeFilter(new AnnotationTypeFilter(Bean.class));
		// 扫描服务模块
		scanModules(scanner, Environment.getApplication().getModules());
	}

	// 扫描模块
	private void scanModules(ClassPathBeanDefinitionScanner scanner, Collection<Module> modules) {
		if (modules != null && modules.size() > 0) {
			for (Module module : modules) {
				String servicePackageName = module.getServicePackageName();
				if (servicePackageName != null && servicePackageName.length() > 0)
					scanner.scan(servicePackageName);
				if (module.isActionModule()) {
					String actionPackageName = module.getActionPackageName();
					if (actionPackageName != null && actionPackageName.length() > 0) {
						scanner.scan(actionPackageName);
					}
				}
			}
		}
	}

	@Override
	protected void postProcessBeanFactory(
			ConfigurableListableBeanFactory beanFactory) {
		super.postProcessBeanFactory(beanFactory);
		// 自动装配
		FrameworkBeanPostProcesser frameworkBeanPostProcesser = new FrameworkBeanPostProcesser();
		frameworkBeanPostProcesser.setBeanFactory(beanFactory);
		beanFactory.addBeanPostProcessor(frameworkBeanPostProcesser);
		// 注册框架对象
		//beanFactory.registerSingleton("persistentService", null);
		//beanFactory.registerSingleton("messageSource", Environment.getApplication().getMessageSource());
	}

}
